<template>
  <div class="system-config">
    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <span>系统配置</span>
          <div class="header-actions">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入配置键名"
              style="width: 300px; margin-right: 10px"
              clearable
              @clear="handleSearch"
              @keydown.enter="handleSearch"
            >
              <template #append>
                <el-button icon="Search" @click="handleSearch" :loading="loading" />
              </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">添加配置</el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="configList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="key" label="键名" width="200" />
        <el-table-column prop="value" label="键值" show-overflow-tooltip />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column prop="updatedAt" label="更新时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑配置对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="configFormRef"
        :model="configForm"
        :rules="configRules"
        label-width="100px"
      >
        <el-form-item label="键名" prop="key">
          <el-input v-model="configForm.key" :maxlength="100" show-word-limit :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="键值" prop="value">
          <el-input v-model="configForm.value" type="textarea" :rows="4" :maxlength="500" show-word-limit />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="configForm.description" type="textarea" :rows="2" :maxlength="200" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { SystemConfig, CreateSystemConfigRequest, UpdateSystemConfigRequest } from '@/types/api/system'
import { systemApi } from '@/api/modules/system'
import { formUtils } from '@/utils'

// 表格相关
const loading = ref(false)
const configList = ref<SystemConfig[]>([])

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页相关
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const saveLoading = ref(false)
const configFormRef = ref()
const currentConfigId = ref(0)

// 表单数据
const configForm = reactive({
  key: '',
  value: '',
  description: ''
})

// 表单验证规则
const configRules = {
  key: [
    { required: true, message: '请输入键名', trigger: 'blur' },
    { max: 100, message: '键名长度不能超过100个字符', trigger: 'blur' }
  ],
  value: [
    { required: true, message: '请输入键值', trigger: 'blur' },
    { max: 500, message: '键值长度不能超过500个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述长度不能超过200个字符', trigger: 'blur' }
  ]
}

// 获取配置列表
const getConfigList = async () => {
  loading.value = true
  try {
    const response = await systemApi.getConfigList({
      page: pagination.page,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword
    })
    configList.value = response.data.data.list
    pagination.total = response.data.data.total
  } catch (error) {
    ElMessage.error('获取配置列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getConfigList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  pagination.page = 1
  getConfigList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.page = val
  getConfigList()
}

// 添加配置
const handleAdd = () => {
  dialogTitle.value = '添加配置'
  isEdit.value = false
  dialogVisible.value = true
  // 重置表单
  Object.assign(configForm, {
    key: '',
    value: '',
    description: ''
  })
}

// 编辑配置
const handleEdit = (row: SystemConfig) => {
  dialogTitle.value = '编辑配置'
  isEdit.value = true
  dialogVisible.value = true
  currentConfigId.value = row.id
  // 填充表单数据
  Object.assign(configForm, {
    key: row.key,
    value: row.value,
    description: row.description
  })
}

// 删除配置
const handleDelete = (row: SystemConfig) => {
  formUtils.handleDeleteConfirm(`配置 "${row.key}"`, async () => {
    await systemApi.deleteConfig(row.id)
    getConfigList()
  }, {
    successMessage: '删除成功',
    errorMessage: '删除失败'
  })
}

// 保存配置信息
const handleSave = async () => {
  if (!configFormRef.value) return

  await configFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      saveLoading.value = true
      try {
        if (isEdit.value) {
          // 编辑配置
          const updateData: UpdateSystemConfigRequest = {
            key: configForm.key,
            value: configForm.value,
            description: configForm.description
          }
          await systemApi.updateConfig(currentConfigId.value, updateData)
          ElMessage.success('更新成功')
        } else {
          // 添加配置
          const createData: CreateSystemConfigRequest = {
            key: configForm.key,
            value: configForm.value,
            description: configForm.description
          }
          await systemApi.createConfig(createData)
          ElMessage.success('添加成功')
        }
        dialogVisible.value = false
        await getConfigList()
      } catch (error: any) {
        ElMessage.error(error.message || (isEdit.value ? '更新失败' : '添加失败'))
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  formUtils.resetForm(configFormRef.value, configForm, {
    key: '',
    value: '',
    description: ''
  })
}

// 初始化
onMounted(() => {
  getConfigList()
})
</script>

<style scoped lang="scss">
.system-config {
  .config-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
